<?php

namespace app\admin\command;

use app\admin\command\Api\library\Builder;


use app\admin\model\SpiderAiqiyi;
use app\admin\model\SpiderAiqiyiCollection;
use app\admin\model\SpiderAiqiyiLog;
use phpspider\core\phpspider;
use think\Config;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use think\Exception;
use phpspider\core\requests;
use phpspider\core\selector;
use think\Model;

class Spider extends Command
{
    protected function configure()
    {
        /* Do NOT delete this comment */
        /* 不要删除这段注释 */
        $this
            ->setName('spider')   //爱奇艺视频抓包
            ->addOption('type', 't', Option::VALUE_REQUIRED, 'type', null)
            ->setDescription("spider 抓包");

    }

    protected function execute(Input $input, Output $output)
    {
        $type = $input->getOption('type');
        //初始更新
        if(empty($type)){
            $list = SpiderAiqiyi::select();
            foreach ($list as $val){
                $url = $val["url"];
                if(empty($url)) continue;
                try{
                    $content = requests::get($url);
                    $album_id = selector::select($content, "/aid=(.*?)&/","regex");//获取albumId 用于获取热度
                    $content_id = selector::select($content, "/tvid=(.*?)&/","regex");//获取content_id 用于获取评论数
                   // $barrage_number = selector::select($content, "//div[@class='func-item func-comment']//span[@class='func-name']");//获取弹幕数
                    $gengxin = selector::select($content, "//p[@class='update-tip']");//获取更新时间，最新集
                    $gengxin = strip_tags($gengxin);
                    $gengxin = trim($gengxin);
                    $gengxin_ar = explode(" ",$gengxin);
                    $hot = $this->hot($album_id);
                    $comment_ar = $this->comment_num($content_id);
                    $comment_number = $comment_ar["comment_number"]??0;
                    $barrage_number = $comment_ar["barrage_number"]??0;
                    $update_data = [
                        "hot"=>(string)$hot,
                        "hot_number"=>$hot,
                        "update_date"=>$gengxin_ar[0],
                        "comment_number"=>$comment_number,
                        "barrage_number"=>$barrage_number,
                        "content_id"=>$content_id,
                        "album_id"=>$album_id
                    ];
                    SpiderAiqiyi::update($update_data,['id'=>$val['id']]);
                }catch (\Exception $e){
                     throw $e;
                }
            }

            return true;
        }

        //更新集数， 一天一次
        if($type=="list"){
            $list = SpiderAiqiyi::select();
            foreach ($list as $val){
                $album_id = $val['album_id'];
                $parent_id = $val["id"];
                $this->collection($album_id,$parent_id);
            }
            return true;
        }

        //更新集的热度，评论数，弹幕数 一小时一次
        if($type=="date"){
            $list = SpiderAiqiyi::select();
            foreach ($list as $val){
                $album_id = $val["album_id"];
                if(empty($album_id)) continue;
                $parent_id = $val["id"];
                if(empty($album_id))
                $update_date = "";
                $hot = "";
                $current_collection = "";
                $collection_list = SpiderAiqiyiCollection::where("parent_id",$parent_id)->select();
                foreach ($collection_list as $val1){
                    $content_id = $val1["content_id"];
                    $url = $val1["url"];
                    if(empty($content_id) || empty($url)) continue;
                    try{
                        $content = requests::get($url);
                       // $barrage_number = selector::select($content, "//div[@class='player-mnb-left']//span[@class='func-name']");//获取弹幕数
                        $gengxin = selector::select($content, "//p[@class='update-tip']");//获取更新时间，最新集
                        $gengxin = strip_tags($gengxin);
                        $gengxin = trim($gengxin);
                        $gengxin_ar = explode(" ",$gengxin);
                        $hot = $this->hot($album_id);
                        $comment_ar = $this->comment_num($content_id);
                        $comment_number = $comment_ar["comment_number"];
                        $barrage_number = $comment_ar["barrage_number"];

                        $update_data = [
                            "comment_number"=>$comment_number,
                            "barrage_number"=>$barrage_number,
                        ];
                        $update_date = $gengxin_ar[0]??"";
                        $current_collection = $gengxin_ar[1]??"";
                        SpiderAiqiyiCollection::update($update_data,['id'=>$val1['id']]);
                    }catch (\Exception $e){
                        throw $e;
                    }
                }
                $hot = $hot?:$val["hot"];
                $update_date = $update_date?:$val['update_date'];
                $current_collection = $current_collection?:$val["current_collection"];
                $total_comment_number = SpiderAiqiyiCollection::where("parent_id",$parent_id)->sum("comment_number");
                $total_barrage_number = SpiderAiqiyiCollection::where("parent_id",$parent_id)->sum("barrage_number");
                $max_hot_number = $val["max_hot_number"]>$hot?$val["max_hot_number"]:$hot;
                $update_data = [
                    "hot"=>(string)$hot,
                    "hot_number"=>$hot,
                    "max_hot_number"=>$max_hot_number,
                    "max_hot"=>(string)$max_hot_number,
                    "update_date"=>$update_date,
                    "current_collection"=>$current_collection,
                    "comment_number"=>$total_comment_number,
                    "barrage_number"=>$total_barrage_number
                ];
                SpiderAiqiyi::update($update_data,["id"=>$parent_id]);

                //日志
                $date = date("Y-m-d");
                $model = SpiderAiqiyiLog::where("parent_id",$parent_id)->where("date",$date)->find();
                if(empty($model)){
                    $model = new SpiderAiqiyiLog();
                }
                $log=[
                    "hot_number"=>$hot,
                    "comment_number"=>$total_comment_number,
                    "barrage_number"=>$total_barrage_number,
                    "date"=>$date,
                    "parent_id"=>$parent_id,
                    "play_number"=>0,
                    "createdtime"=>time()
                ];
                $model->save($log);

            }
            return true;
        }

    }

    //获取热度
    protected function hot($albumId){
        $url = "https://pcw-api.iqiyi.com/video/video/hotplaytimes/".$albumId;
        $hot = 0;
        try{
            $content =  requests::get($url);
            $ar = json_decode($content,true);
            $hot = $ar['data'][0]['hot']??0;
            return $hot;
        }catch (\GuzzleHttp\Exception\RequestException $e){
            // throw $e;
//            $response = $e->getResponse();
//            $code=$response->getStatusCode();
//            $content = $response->getBody()->getContents();
//            p($code);
//            p($content);
//            p($e->getMessage());die;
            return $hot;
        }

        return $hot;
    }

    //获取评论数
    protected function comment_num($content_id){
        $url ="https://sns-comment.iqiyi.com/v3/comment/get_comments.action?agent_type=118&business_type=17&content_id=".$content_id;
        try{
            $content = requests::get($url);
            $data = json_decode($content,true);
            //$pinglun_num =  selector::select($content, "/commentReplyCount\":(.*?),/","regex");// 评论数
            $comment_number = $data['data']["commentReplyCount"]??0;
            $barrage_number = $data['data']["totalCount"]??0;
            return ["comment_number"=>$comment_number,"barrage_number"=>$barrage_number];
        }catch (\Exception $e){

        }
        return ["comment_number"=>0,"barrage_number"=>0];
    }

    //集数
    protected function collection($album_id,$parent_id){

        $url = "https://pcw-api.iqiyi.com/albums/album/avlistinfo?aid=$album_id&page=1&size=500";
        try{
            $content = requests::get($url);
            $ar = json_decode($content,true);
            $epsodelist = $ar['data']['epsodelist']??[];
            $updateprevuelist = $ar['data']['updateprevuelist']??[];
            $arr = array_merge($epsodelist,$updateprevuelist);
            $list = [];
            foreach ($arr as $val){
                $list[]=[
                    "content_id"=>(string)$val['tvId'],
                    "collection"=>$val['name'],
                    "url"=>$val['playUrl'],
                    "parent_id"=>$parent_id
                ];
            }

            $model =  new \app\admin\model\SpiderAiqiyiCollection;
            $collection_list = $model->select();
            $content_ar = $collection_list?array_column($collection_list,"content_id"):[];

            foreach ($list as $list_val){
                if(!in_array($list_val['content_id'],$content_ar)){
                    $new_model = clone $model;
                    $new_model->save($list_val);
                }
            }

        }catch (\Exception $e){

        }
    }

}
